package com.example.cm_player.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.v4.media.session.MediaSessionCompat
import androidx.core.app.NotificationCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.example.cm_player.model.SongInfo
import com.example.cm_player.R

/**
 * 音乐播放通知管理类
 * 提供简洁方法创建和更新音乐播放通知
 */
class NotificationHelper private constructor() {
    companion object {
        private const val CHANNEL_ID = "music_player_channel"
        private const val NOTIFICATION_ID = 1

        // 操作常量
        const val ACTION_PLAY = "com.example.cm_player.ACTION_PLAY"
        const val ACTION_PAUSE = "com.example.cm_player.ACTION_PAUSE"
        const val ACTION_PREVIOUS = "com.example.cm_player.ACTION_PREVIOUS"
        const val ACTION_NEXT = "com.example.cm_player.ACTION_NEXT"
        const val ACTION_CLOSE = "com.example.cm_player.ACTION_CLOSE"

        // 单例
        @Volatile
        private var instance: NotificationHelper? = null

        fun getInstance(): NotificationHelper {
            return instance ?: synchronized(this) {
                instance ?: NotificationHelper().also { instance = it }
            }
        }
    }

    private var notificationManager: NotificationManager? = null
    private var mediaSession: MediaSessionCompat? = null
    private var builder: NotificationCompat.Builder? = null
    private var mainActivityClass: Class<*>? = null

    /**
     * 初始化通知助手
     * @param context 上下文
     * @param mainActivityClass 点击通知时启动的Activity类
     */
    fun init(context: Context, mainActivityClass: Class<*>) {
        this.mainActivityClass = mainActivityClass
        notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        createNotificationChannel(context)

        // 创建MediaSession
        mediaSession = MediaSessionCompat(context, "MusicPlayer").apply {
            isActive = true
        }
    }

    /**
     * 创建通知渠道（Android 8.0+需要）
     */
    private fun createNotificationChannel(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "音乐播放",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "控制音乐播放"
                setShowBadge(false)
                enableLights(false)
                enableVibration(false)
            }
            notificationManager?.createNotificationChannel(channel)
        }
    }

    /**
     * 创建通知
     * @param context 上下文
     * @param songInfo 当前播放的歌曲信息
     * @param isPlaying 是否正在播放
     * @param pendingIntentProvider 创建PendingIntent的回调
     * @return 创建的通知对象
     */
    fun createNotification(
        context: Context,
        songInfo: SongInfo,
        isPlaying: Boolean,
        pendingIntentProvider: (String) -> PendingIntent
    ): Notification {
        // 构建通知
        builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_music_default)
            .setContentTitle(songInfo.title)
            .setContentText(songInfo.artist)
            .setOnlyAlertOnce(true)
            .setOngoing(isPlaying)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)

        // 添加按钮
        builder?.addAction(
            R.drawable.ic_media_previous,
            "上一曲",
            pendingIntentProvider(ACTION_PREVIOUS)
        )

        // 播放/暂停按钮
        val playPauseAction = if (isPlaying) {
            NotificationCompat.Action(
                R.drawable.ic_media_pause,
                "暂停",
                pendingIntentProvider(ACTION_PAUSE)
            )
        } else {
            NotificationCompat.Action(
                R.drawable.ic_media_play,
                "播放",
                pendingIntentProvider(ACTION_PLAY)
            )
        }
        builder?.addAction(playPauseAction)

        // 下一曲按钮
        builder?.addAction(
            R.drawable.ic_media_next,
            "下一曲",
            pendingIntentProvider(ACTION_NEXT)
        )

        // 关闭按钮
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+可以使用系统的关闭按钮
            builder?.setAutoCancel(true)
                ?.setDeleteIntent(pendingIntentProvider(ACTION_CLOSE))
        } else {
            // 添加自定义关闭按钮
            builder?.addAction(
                android.R.drawable.ic_menu_close_clear_cancel,
                "关闭",
                pendingIntentProvider(ACTION_CLOSE)
            )
        }

        // 添加内容意图
        val contentIntent = PendingIntent.getActivity(
            context,
            0,
            Intent(context, mainActivityClass),
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        builder?.setContentIntent(contentIntent)

        // 设置媒体样式
        builder?.setStyle(
            androidx.media.app.NotificationCompat.MediaStyle()
                .setMediaSession(mediaSession?.sessionToken)
                .setShowActionsInCompactView(0, 1, 2)
        )

        // 加载歌曲封面
        loadAlbumArt(context, songInfo.imageUrl)

        return builder?.build() ?: throw IllegalStateException("无法创建通知")
    }

    /**
     * 更新播放状态
     * @param isPlaying 是否正在播放
     * @param pendingIntentProvider 创建PendingIntent的回调
     */
    fun updatePlaybackState(
        isPlaying: Boolean,
        pendingIntentProvider: (String) -> PendingIntent
    ) {
        // 更新播放/暂停按钮
        val action = if (isPlaying) {
            NotificationCompat.Action(
                R.drawable.ic_media_pause,
                "暂停",
                pendingIntentProvider(ACTION_PAUSE)
            )
        } else {
            NotificationCompat.Action(
                R.drawable.ic_media_play,
                "播放",
                pendingIntentProvider(ACTION_PLAY)
            )
        }

        // 替换第二个操作（播放/暂停按钮）
        builder?.mActions?.set(1, action)
        builder?.setOngoing(isPlaying)

        // 更新通知
        notificationManager?.notify(NOTIFICATION_ID, builder?.build())
    }

    /**
     * 加载专辑封面
     * @param context 上下文
     * @param imageUrl 图片URL
     */
    private fun loadAlbumArt(context: Context, imageUrl: String) {
        Glide.with(context)
            .asBitmap()
            .load(imageUrl)
            .error(R.drawable.ic_music_default)
            .into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    builder?.setLargeIcon(resource)
                    notificationManager?.notify(NOTIFICATION_ID, builder?.build())
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    // 加载失败时使用默认图标
                    notificationManager?.notify(NOTIFICATION_ID, builder?.build())
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // 不需要处理
                }
            })
    }

    /**
     * 显示通知
     */
    fun showNotification(notification: Notification) {
        notificationManager?.notify(NOTIFICATION_ID, notification)
    }

    /**
     * 取消通知
     */
    fun cancelNotification() {
        notificationManager?.cancel(NOTIFICATION_ID)
    }


    /**
     * 获取通知ID
     */
    fun getNotificationId(): Int = NOTIFICATION_ID

    /**
     * 释放资源
     */
    fun release() {
        mediaSession?.release()
        mediaSession = null
        builder = null
        notificationManager = null
        instance = null
    }
}